package cn.clx.user.service.impl;

import cn.clx.basic.dto.RegisterDto;
import cn.clx.basic.exception.BusinessException;
import cn.clx.basic.util.MD5Utils;
import cn.clx.basic.util.StrUtils;
import cn.clx.user.domain.Logininfo;
import cn.clx.user.domain.User;
import cn.clx.user.mapper.LogininfoMapper;
import cn.clx.user.mapper.UserMapper;
import cn.clx.user.service.IUserService;
import cn.clx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author clx
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param dto
     */
    @Override
    public void register(RegisterDto dto) {

        //校验
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        String phonecodekey="register:"+dto.getPhone();
        Object phonevalue = redisTemplate.opsForValue().get(phonecodekey);
        if(phonevalue==null){
            throw new BusinessException("短信验证码以过期，请重新获取");
        }
        String smsCode = dto.getSmsCode();
        String phonecode = phonevalue.toString().split(":")[0];
        if(!smsCode.equalsIgnoreCase(phonecode)){
            throw new BusinessException("验证码输入不正确，请重新输入");
        }
        //就不进行phone电话的校验了，校验此电话号码被注册了没有，最好还是校验一下
        User user =dto2user(dto);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    /**
     * 邮箱注册
     * @param dto
     */
    @Override
    public void emailregister(RegisterDto dto) {
        String email = dto.getEmail();
        String emailCode = dto.getEmailCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        String imageCodeKey = dto.getImageCodeKey();
        //校验
        if(!StringUtils.hasLength(email)||
                !StringUtils.hasLength(emailCode)||
                !StringUtils.hasLength(password)||
                !StringUtils.hasLength(passwordRepeat)||
                !StringUtils.hasLength(imageCodeKey)
        ){
            throw new BusinessException("参数不能为空");
        }

        //两次密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("两次密码不一致");
        }
        Object imageValue = redisTemplate.opsForValue().get(imageCodeKey);
        if(imageValue==null){
            throw new BusinessException("图形验证码已过期，请重试");
        }
        if(!imageValue.toString().equalsIgnoreCase(emailCode)){
            throw new BusinessException("图形验证码错误，请重新填写");
        }
        User user = userMapper.loadByEmail(email);
        if(user!=null){
            throw new BusinessException("该用户已存在，请直接登陆");
        }
        User dto2user = dto2useremail(dto);
        Logininfo logininfo = new Logininfo();
        //把dto2user和logininfo的公共属性，传递给logininfo
        BeanUtils.copyProperties(dto2user,logininfo);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);
        dto2user.setLogininfoId(logininfo.getId());
        userMapper.save(dto2user);

    }
    //email的初始化user
    private User dto2useremail(RegisterDto dto) {
        User user = new User();
        user.setPassword(MD5Utils.encrypByMd5(dto.getPassword()+StrUtils.getComplexRandomString(16)));
        user.setSalt(StrUtils.getComplexRandomString(16));
        user.setEmail(dto.getEmail());
        return user;
    }

    //初始化user
    private User dto2user(RegisterDto dto) {
        User user = new User();
        String phone = dto.getPhone();
        String password = dto.getPassword();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(16);
        user.setSalt(salt);
        user.setPassword(MD5Utils.encrypByMd5(password+salt));
        return user;

    }

    /**
     * 修改user同时要修改logininfo表
     * @param user
     */
    @Override
    public void update(User user) {
        Logininfo logininfo=user2updatelogininfo(user);
        user.setLogininfoId(logininfo.getId());
        super.update(user);
    }

    private Logininfo user2updatelogininfo(User user) {
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.update(logininfo);
        return logininfo;
    }
}
